package org.mj.hz.converter.xml;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

public class MjDom4jConverter implements MjXmlConverter{

    static Log log = LogFactory.get();
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> targetType) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document parse = null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            parse = documentBuilder.parse(byteArrayInputStream);
        } catch (SAXException | ParserConfigurationException | IOException e) {
            log.error(e);
            throw new RuntimeException(e);
        }
        return   XmlUtil.xmlToBean(parse,targetType);

    }
}
